import React, {useState} from "react";
import {trim} from "lodash";
import {Modal, Form, Input} from "antd/lib";
import { wrap as wrapDialog, DialogPropType } from "@/components/DialogWrapper";
import DynamicComponent from "@/components/DynamicComponent";
import {policy} from "@/services/policy";
import Enums from "@/services/enums";
import notification from "@/services/notification";

function CreateEnumsDialog({dialog }) {
  const [code, setCode] = useState("");
  const [name, setName] = useState("");
  const [isValid, setIsValid] = useState(false);
  const [saveInProgress, setSaveInProgress] = useState(false);
  const isCreateEnumsEnabled = policy.isAdmin() || policy.isDefault();

  function handleCodeChange(event) {
    const value = trim(event.target.value);
    setCode(value);
    setIsValid(value !== "" && name !== "");
  }

  function handleNameChange(event) {
    const value = trim(event.target.value);
    setName(value);
    setIsValid(value !== "" && code !== "");
  }

  function handleSubmit() {
    setSaveInProgress(true);

    Enums.create({code: code, name: name})
      .then(() => {
        dialog.close({ success: true});
      })
      .catch(error => {
        notification.error(error.message, error.detailedMessage);
        setSaveInProgress(false);
      });
  }

  return (
    <Modal
      {...dialog.props}
      {...(isCreateEnumsEnabled ? {} : { footer: null })}
      title="枚举类型"
      okText="保存"
      cancelText="取消"
      okButtonProps={{
        disabled: !isValid || saveInProgress,
        loading: saveInProgress,
        "data-test": "DashboardSaveButton",
      }}
      cancelButtonProps={{
        disabled: saveInProgress,
      }}
      onOk={handleSubmit}
      closable={!saveInProgress}
      maskClosable={!saveInProgress}
      wrapProps={{
        "data-test": "CreateDashboardDialog",
      }}>
      <DynamicComponent name="CreateEnumsDialogExtra" disabled={!isCreateEnumsEnabled}>
      <Form>
        <Form.Item style={{ marginBottom: 5 }} label="代码">
        <Input
          defaultValue={code}
          onChange={handleCodeChange}
          placeholder="代码"
          disabled={saveInProgress}
          autoFocus
        />
        </Form.Item>
        <Form.Item style={{ marginBottom: 5 }} label="名称">
        <Input
          defaultValue={name}
          onChange={handleNameChange}
          placeholder="名称"
          disabled={saveInProgress}
        />
        </Form.Item>
      </Form>
      </DynamicComponent>
    </Modal>
  );
}

CreateEnumsDialog.propTypes = {
  dialog: DialogPropType.isRequired,
};

export default wrapDialog(CreateEnumsDialog);
